//axios 基础的封装
//配置axios
import axios from 'axios'
import {useUserStore} from "@/stores/user";

// /********** 携带session ************/
axios.defaults.withCredentials = true; //保持sessionId不变
// import {ElMessage, ElMessageBox} from "element-plus";
const userStore = useUserStore()
// 创建axios实例
const request = axios.create({
    withCredentials:true,
    baseURL: '/api',
})

// axios请求拦截器

request.interceptors.request.use(config => {
    if (userStore.token) {
        // console.log(userStore.token)
        config.headers.Authorization = `Bearer ${userStore.token}`
    }
    return config
}, error => Promise.reject(error))

request.interceptors.response.use(

    response => {
        const { code, msg } = response.data;
        if (code === 200) {
            return response.data;
        }
        // 响应数据为二进制流处理(Excel导出)
        if (response.data instanceof ArrayBuffer) {
            return response;
        }
        /**
         *  10011 需要登录
         *  10010 验证失败 —— 访问了不属于TA的接口
         *  403 没有权限
         */
        if (code === 10011) {
            ElMessageBox.alert("当前页面已失效，请重新登录", "提示", {
                confirmButtonText: "确定",
                type: "warning",
            }).then(() => userStore.reset());
        }
        ElMessage.error(msg|| "系统出错，请稍后再试")
        return Promise.reject(new Error(msg || "系统出错，请稍后再试"));

    },
    //接口错误状态处理，也就是说无响应时的处理
    error => {
        return Promise.reject(error.message);//接口返回的错误信息
    }
)

export default request